<?php
/**
 * 调用腾讯地图接口
 * @author 王涛
 * @DataTime 2018-08-04T16:47:34+0800
 */
namespace app\api\controller;

use think\Controller;
use think\Request;

class Map extends Controller {
    /**
     * 地图 附近信息
     * @author zhenHong~ 接口重写
     * 请求类型：get请求
     * 搜索结果支持三种类型：1、指定地区名称region  2、周边搜索nearby  3、矩形搜索rectangle
     * 请求地址：https://apis.map.qq.com/ws/place/v1/search?keyword=酒店&boundary=nearby(39.908491,116.374328,1000)&key=AJ2BZ-3U7EX-GGE45-7MYBE-Z7VIO-IXFA7
     *  必选参数：
     *          keyword-关键字
     *          boundary-地理范围
     *          key-开发者秘钥
     *          lat-纬度
     *          lng-经度
     *          page_size  每页条数
     *          page_index  页数
     * linux下的PHP，就必须安装openssl模块
     *     extension=php_openssl.dll
     *     allow_url_include = On
     */
    public function nearby(Request $request)
    {
        $postData = $request->post();
        $result = $this->validate($postData,'MapValidate');
        if($result !== true){
            return apiResponse(201,$result,"");
        }else{
            $url = "https://apis.map.qq.com/ws/place/v1/search?keyword=".$postData['keyword']."&boundary=nearby(".$postData['lat'].",".$postData['lng'].",5000)&page_size=".$postData['page_size']."&page_index=".$postData['page_index']."&orderby=_distance&key=AJ2BZ-3U7EX-GGE45-7MYBE-Z7VIO-IXFA7";
            $content = file_get_contents($url);
            $content = json_decode($content, true);
            $content = array_map(function($data){
                $data['_distance'] = number_format(($data['_distance'] / 1000),1);
                return $data;
            },$content['data']);
            $distance = [];
            foreach ($content as $item){
                $distance[] = $item['_distance'];
            }
            array_multisort($distance,SORT_ASC,$content);
            return apiResponse(200,"成功", $content);
        }
    }
    /**
     * 通过经纬度查询地名
     * @author 王涛
     * @DataTime 2018-08-10T18:08:31+0800
     * @return   [type]                   [description]
     * https://apis.map.qq.com/ws/geocoder/v1/?
     *  location= 39.984154,116.307490
     * get_poi=1
     * poi_options=address_format=short;radius=5000;
     * page_size=20;page_index=1;policy=2
     */
    public function address($lon,$lat)
    {
            $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=" . $lon . "," . $lat . "&get_poi=0&key=AJ2BZ-3U7EX-GGE45-7MYBE-Z7VIO-IXFA7";
            $content = file_get_contents($url);
            $content = json_decode($content, true);
            if($content['status'] != 0 ){
                return "未知区域！";
            }
            return $content['result']['address'];

    }
}